package com.citms.mq;

import com.citms.remote.model.RabbitMQConfigModel;
import com.citms.remote.service.ConfigService;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(RabbitProperties.class)
public class RabbitConfig {

    @Autowired
    public ConfigService configService;

    @Bean
    public RabbitMQConfigModel getRabbitMQConfigModel(){
        RabbitMQConfigModel config = configService.getRabbitMQConfig();
        if(config==null){
            throw new RuntimeException("从微服务获取消息队列配置信息出错");
        }
        return config;
    }

    @Bean
    public ConnectionFactory connectionFactory(RabbitProperties rabbitProperties,RabbitMQConfigModel config) {
        buildRabbitProperties(rabbitProperties,config);//通过系统管理微服务获取配置构建rabbitProperties
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(rabbitProperties.getHost(),
                rabbitProperties.getPort());
        connectionFactory.setUsername(rabbitProperties.getUsername());
        connectionFactory.setPassword(rabbitProperties.getPassword());
        return connectionFactory;
    }

    private void buildRabbitProperties(RabbitProperties rabbitProperties,RabbitMQConfigModel config) {
        rabbitProperties.setHost(config.getHost());
        rabbitProperties.setPort(config.getPort());
        rabbitProperties.setUsername(config.getUserName());
        rabbitProperties.setPassword(config.getPassword());
    }



}
